<template>
  <div class="roles-page">
    <div class="page-header">
      <h1>角色管理</h1>
      <p>管理系统角色信息</p>
    </div>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.roleCode"
            placeholder="请输入角色编码"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 100%"
          >
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </template>

      <el-table
        :data="roleList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleCode" label="角色编码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-container">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="success" size="small" @click="handleAssignUsers(row)">
                分配用户
              </el-button>
              <el-button
                :type="row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number
            v-model="roleForm.sortOrder"
            :min="0"
            :max="999"
            placeholder="请输入排序号"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配用户对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配用户"
      width="800px"
      @close="handleAssignDialogClose"
    >
      <div class="assign-content">
        <div class="assign-header">
          <span>为角色 "{{ currentRole.roleName }}" 分配用户</span>
        </div>
        
        <!-- 用户搜索 -->
        <el-row :gutter="20" style="margin-bottom: 16px;">
          <el-col :span="12">
            <el-input
              v-model="userSearchForm.username"
              placeholder="搜索用户名"
              clearable
              @keyup.enter="handleUserSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="handleUserSearch">搜索</el-button>
            <el-button @click="handleUserSearchReset">重置</el-button>
          </el-col>
        </el-row>

        <!-- 用户列表 -->
        <el-table
          :data="userList"
          v-loading="userLoading"
          style="width: 100%"
          @selection-change="handleUserSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="realName" label="真实姓名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否已分配" width="100">
            <template #default="{ row }">
              <el-tag v-if="isUserAssigned(row.id)" type="success">已分配</el-tag>
              <el-tag v-else type="info">未分配</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignSubmit" :loading="assignLoading">
            确定分配
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Key,
  Refresh,
  Plus
} from '@element-plus/icons-vue'
import * as roleApi from '@/api/role'
import * as userApi from '@/api/user'

/**
 * 表单引用
 */
const roleFormRef = ref()

/**
 * 加载状态
 */
const loading = ref(false)
const submitLoading = ref(false)
const userLoading = ref(false)
const assignLoading = ref(false)

/**
 * 对话框状态
 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const assignDialogVisible = ref(false)

/**
 * 搜索表单
 */
const searchForm = reactive({
  roleName: '',
  roleCode: '',
  status: ''
})

/**
 * 用户搜索表单
 */
const userSearchForm = reactive({
  username: ''
})

/**
 * 角色表单
 */
const roleForm = reactive({
  id: null,
  roleName: '',
  roleCode: '',
  description: '',
  sortOrder: 0,
  status: 1
})

/**
 * 当前操作的角色
 */
const currentRole = ref({})

/**
 * 表单验证规则
 */
const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '角色编码长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

/**
 * 角色列表
 */
const roleList = ref([])

/**
 * 用户列表
 */
const userList = ref([])

/**
 * 选中的角色
 */
const selectedRoles = ref([])

/**
 * 选中的用户
 */
const selectedUsers = ref([])

/**
 * 已分配的用户ID列表
 */
const assignedUserIds = ref([])

/**
 * 分页信息
 */
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

/**
 * 获取角色列表
 */
const getRoleList = async () => {
  try {
    loading.value = true
    
    const params = {
      current: pagination.page,
      size: pagination.size,
      roleName: searchForm.roleName || undefined,
      roleCode: searchForm.roleCode || undefined,
      status: searchForm.status !== '' ? searchForm.status : undefined
    }
    
    const response = await roleApi.getRolePage(params)
    
    if (response.code === 200) {
      roleList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
    
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取用户列表
 */
const getUserList = async () => {
  try {
    userLoading.value = true
    
    const params = {
      current: 1,
      size: 100, // 获取所有用户用于分配
      username: userSearchForm.username || undefined
    }
    
    const response = await userApi.getUserPage(params)
    
    if (response.code === 200) {
      userList.value = response.data.records || []
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
    
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    userLoading.value = false
  }
}

/**
 * 获取角色已分配的用户
 */
const getRoleUsers = async (roleId) => {
  try {
    const response = await roleApi.getUserRoleList({ roleId })
    
    if (response.code === 200) {
      assignedUserIds.value = response.data.map(item => item.userId) || []
    } else {
      ElMessage.error(response.message || '获取角色用户失败')
    }
    
  } catch (error) {
    console.error('获取角色用户失败:', error)
    ElMessage.error('获取角色用户失败')
  }
}

/**
 * 检查用户是否已分配
 */
const isUserAssigned = (userId) => {
  return assignedUserIds.value.includes(userId)
}

/**
 * 搜索角色
 */
const handleSearch = () => {
  pagination.page = 1
  getRoleList()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    roleName: '',
    roleCode: '',
    status: ''
  })
  handleSearch()
}

/**
 * 搜索用户
 */
const handleUserSearch = () => {
  getUserList()
}

/**
 * 重置用户搜索
 */
const handleUserSearchReset = () => {
  Object.assign(userSearchForm, {
    username: ''
  })
  handleUserSearch()
}

/**
 * 新增角色
 */
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  resetRoleForm()
  dialogVisible.value = true
}

/**
 * 编辑角色
 */
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, { ...row })
  dialogVisible.value = true
}

/**
 * 分配用户
 */
const handleAssignUsers = async (row) => {
  currentRole.value = { ...row }
  assignDialogVisible.value = true
  await getUserList()
  await getRoleUsers(row.id)
}

/**
 * 切换角色状态
 */
const handleToggleStatus = async (row) => {
  try {
    const action = row.status === 1 ? '禁用' : '启用'
    await ElMessageBox.confirm(
      `确定要${action}角色 "${row.roleName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const newStatus = row.status === 1 ? 0 : 1
    const response = await roleApi.updateRoleStatus(row.id, { status: newStatus })
    
    if (response.code === 200) {
      row.status = newStatus // 更新本地状态
      ElMessage.success(`${action}成功`)
    } else {
      ElMessage.error(response.message || `${action}失败`)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换角色状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

/**
 * 删除角色
 */
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.roleName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleApi.deleteRole(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getRoleList() // 重新获取列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    submitLoading.value = true
    
    let response
    if (roleForm.id) {
      // 编辑
      response = await roleApi.updateRole(roleForm.id, roleForm)
    } else {
      // 新增
      response = await roleApi.createRole(roleForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(roleForm.id ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      getRoleList() // 重新获取列表
    } else {
      ElMessage.error(response.message || '操作失败')
    }
    
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

/**
 * 提交用户分配
 */
const handleAssignSubmit = async () => {
  try {
    assignLoading.value = true
    
    const userIds = selectedUsers.value.map(user => user.id)
    const response = await roleApi.assignUserRole({
      roleId: currentRole.value.id,
      userIds: userIds
    })
    
    if (response.code === 200) {
      ElMessage.success('分配成功')
      assignDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '分配失败')
    }
    
  } catch (error) {
    console.error('分配用户失败:', error)
    ElMessage.error('分配失败')
  } finally {
    assignLoading.value = false
  }
}

/**
 * 重置角色表单
 */
const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: null,
    roleName: '',
    roleCode: '',
    description: '',
    sortOrder: 0,
    status: 1
  })
  
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
}

/**
 * 对话框关闭
 */
const handleDialogClose = () => {
  resetRoleForm()
}

/**
 * 分配对话框关闭
 */
const handleAssignDialogClose = () => {
  selectedUsers.value = []
  assignedUserIds.value = []
  currentRole.value = {}
}

/**
 * 选择变化
 */
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

/**
 * 用户选择变化
 */
const handleUserSelectionChange = (selection) => {
  selectedUsers.value = selection
}

/**
 * 页面大小变化
 */
const handleSizeChange = (size) => {
  pagination.size = size
  getRoleList()
}

/**
 * 当前页变化
 */
const handleCurrentChange = (page) => {
  pagination.page = page
  getRoleList()
}

/**
 * 组件挂载时执行
 */
onMounted(() => {
  getRoleList()
})
</script>

<style scoped>
.roles-page {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.assign-content {
  max-height: 500px;
  overflow-y: auto;
}

.assign-header {
  margin-bottom: 16px;
  font-weight: 600;
  color: #303133;
}

/* 操作按钮容器样式 */
.action-buttons-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 8px;
  align-items: center;
  justify-content: flex-start;
  line-height: 1.2;
}

/* 操作按钮样式优化 */
:deep(.el-button--small) {
  padding: 5px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin: 0;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #3a8ee6);
  border: none;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #5daf34);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f25c5c);
  border: none;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #e6a23c, #d19e2a);
  border: none;
}

.danger {
  color: #f56c6c;
}

.success {
  color: #67c23a;
}

:deep(.el-table .el-button--text) {
  padding: 0;
  margin-right: 8px;
}

:deep(.el-table .el-button--text:last-child) {
  margin-right: 0;
}
</style>